import { IpcMainInvokeEvent, app, dialog, globalShortcut, ipcMain } from 'electron'
import { IPCEvent } from '@common/constant'
import { getWindowByName } from './windows'
import { findOne } from './db/query'

// handle方法对应invoke方法,invoke方法返回的是Promise，异步
ipcMain.handle(IPCEvent.SHORTCUT, (_event: IpcMainInvokeEvent, shortcut: string) => {
  return registerSearchShortcut(shortcut)
})

function registerSearchShortcut(shortcut: string): boolean {
  globalShortcut.unregisterAll()

  // 判断系统是否已经注册了相同快捷键，如果已经注册了就直接返回false
  if (shortcut && globalShortcut.isRegistered(shortcut)) {
    dialog.showErrorBox('温馨提示', '快捷键注册失败,请检查快捷键是否已被占用')
    return false
  }
  // 默认注册一个数据库的快捷键(可以修改)，用来控制窗口的显示或隐藏
  const win = getWindowByName('search')
  return globalShortcut.register(shortcut, () => {
    // 显示或隐藏code窗口
    win.isVisible() ? win.hide() : win.show()
  })
}

app.on('will-quit', () => {
  // 注销所有快捷键
  globalShortcut.unregisterAll()
})

export const registerAppGlobleShortcut = async () => {
  const config = (await findOne('SELECT * FROM config WHERE id = 1;')) as ConfigType
  const shortcut = (JSON.parse(config.content) as ConfigContentType).shortcut
  // 注册快捷键
  if (shortcut) {
    registerSearchShortcut(shortcut)
  }
}
